<script lang="ts" setup>
import dayjs from 'dayjs'
import type { FormInst, FormItemRule, FormRules } from 'naive-ui'
import { myGoodsDetail, myGoodsModify } from '@/api/goods'
import type { MyGoodsModifySendModel } from '@/api/goods'
import type { FileItemModel } from '@/api/file'

interface Props {
  goodsId: string
}
const props = withDefaults(defineProps<Props>(), {
  goodsId: '', // 商品id
})

// 修改商品表单数据
const goodsItem = ref<MyGoodsModifySendModel>({
  id: '',
  parentId: null,
  name: '',
  iconId: '',
  homeImageIds: '',
  detailsImageIds: '',
  hot: '',
  stock_num: null,
  price: null,
  oldPrice: null,
  none_sku: true,
})

// 获取商品数据
onMounted(() => {
  if (props.goodsId) {
    goodsItem.value.id = props.goodsId
    getDetail()
  }
})
const goodsItemIconList = ref<FileItemModel[]>([])
const goodsItemHomeImageIdsList = ref<FileItemModel[]>([])
const goodsItemDetailsImageIdsList = ref<FileItemModel[]>([])
async function getDetail() {
  const { code, data } = await myGoodsDetail({ goodsId: props.goodsId })
  if (code === 0) {
    goodsItem.value.id = data.id
    goodsItem.value.parentId = data.parentId
    goodsItem.value.name = data.name
    goodsItem.value.hot = data.hot
    goodsItem.value.stock_num = data.stock_num
    goodsItem.value.price = Number(data.price)
    goodsItem.value.oldPrice = Number(data.oldPrice)
    goodsItem.value.none_sku = !!data.none_sku

    // 文件id 文件列表处理
    goodsItem.value.iconId = data.iconId.map(item => item.id).toString()
    goodsItemIconList.value = data.iconId

    goodsItem.value.homeImageIds = data.homeImageIds.map(item => item.id).toString()
    goodsItemHomeImageIdsList.value = data.homeImageIds

    goodsItem.value.detailsImageIds = data.detailsImageIds.map(item => item.id).toString()
    goodsItemDetailsImageIdsList.value = data.detailsImageIds
  }
}
// 表单校验
const rulesFunction = {
  parentIdValidator(_rule: FormItemRule, value: number): boolean {
    return !!value
  },
  uploadValidator(_rule: FormItemRule, value: string): boolean {
    return !!value
  },
}
const rules: FormRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  hot: [{ required: true, message: '请输入商品标签', trigger: 'blur' }],
  oldPrice: [{ required: true, message: '请输入商品展示原价', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品展示现价', trigger: 'blur' }],
  stock_num: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择商品类别', trigger: 'change', validator: rulesFunction.parentIdValidator }],
  iconId: [{ required: true, message: '请上传商品封面', trigger: 'change', validator: rulesFunction.uploadValidator }],
  homeImageIds: [{ required: true, message: '请上传商品展示图片', trigger: 'change', validator: rulesFunction.uploadValidator }],
  detailsImageIds: [{ required: true, message: '请上传商品详情图片', trigger: 'change', validator: rulesFunction.uploadValidator }],
}
// 提交表单
const goodsModifyRef = ref<FormInst | null>(null)
async function submitForm() {
  goodsModifyRef.value?.validate((errors) => {
    if (!errors)
      goodModify()
    else
      window.$message?.warning('请输入相应必填项')
  })
}
async function goodModify() {
  const { code, msg } = await myGoodsModify(goodsItem.value)
  if (code === 0)
    window.$message?.success(msg)
}
// 重置表单
function resetForm() {
  goodsItem.value = {
    id: '',
    parentId: null,
    name: '',
    iconId: '',
    homeImageIds: '',
    detailsImageIds: '',
    hot: '',
    stock_num: null,
    price: null,
    oldPrice: null,
    none_sku: true,
  }
  goodsItemIconList.value = []
  goodsItemHomeImageIdsList.value = []
  goodsItemDetailsImageIdsList.value = []
  goodsModifyRef.value?.restoreValidation() // 清空校验
  window.$message?.success('重置成功')
}
</script>

<template>
  <AppPage class="goods-modify">
    <n-form
      ref="goodsModifyRef"
      :model="goodsItem"
      :rules="rules"
      size="medium"
      label-placement="top"
    >
      <n-alert type="warning" closable :bordered="true" mb-10>
        多个规格的商品请继续在《规格管理》菜单中完善相应信息
      </n-alert>
      <n-form-item label="上架时间">
        {{ dayjs(new Date()).format('YYYY-MM-DD') }}
      </n-form-item>
      <n-form-item label="商品封面" path="iconId">
        <CuploadImage v-model:imageIds="goodsItem.iconId" :default-file-list="goodsItemIconList" :max="1" width="150px" height="150px" />
      </n-form-item>
      <n-form-item label="商品类别" path="parentId">
        <Ccascader v-model:categoryId="goodsItem.parentId" w-200 />
      </n-form-item>
      <n-form-item label="商品名称" path="name">
        <n-input v-model:value="goodsItem.name" placeholder="输入商品名称" />
      </n-form-item>
      <n-form-item label="商品标签" path="hot">
        <n-input v-model:value="goodsItem.hot" placeholder="输入商品标签,最大长度10个字符" />
      </n-form-item>
      <n-form-item label="商品展示原价" path="oldPrice">
        <n-input-number v-model:value="goodsItem.oldPrice" :show-button="false" placeholder="输入商品展示原价" w-full />
      </n-form-item>
      <n-form-item label="商品展示现价" path="price">
        <n-input-number v-model:value="goodsItem.price" :show-button="false" placeholder="输入商品展示现价" w-full />
      </n-form-item>
      <n-form-item label="商品库存" path="stock_num">
        <n-input-number v-model:value="goodsItem.stock_num" :show-button="false" placeholder="输入商品总库存" w-full />
      </n-form-item>
      <n-form-item label="商品展示图片" path="homeImageIds">
        <CuploadImage v-model:imageIds="goodsItem.homeImageIds" :default-file-list="goodsItemHomeImageIdsList" width="150px" height="150px" />
      </n-form-item>
      <n-form-item label="商品详情图片" path="detailsImageIds">
        <CuploadImage v-model:imageIds="goodsItem.detailsImageIds" :default-file-list="goodsItemDetailsImageIdsList" width="150px" height="150px" />
      </n-form-item>
      <n-form-item label="是否无规格商品">
        <n-switch v-model:value="goodsItem.none_sku" :round="false" />
      </n-form-item>
    </n-form>
    <n-space>
      <n-button type="primary" size="medium" text-14 w-150 @click="submitForm">
        <template #icon>
          <icon-mdi:content-save-edit />
        </template>
        提 交
      </n-button>
      <n-button type="default" size="medium" text-14 w-150 @click="resetForm">
        <template #icon>
          <icon-system-uicons:reset />
        </template>
        重 置
      </n-button>
    </n-space>
  </AppPage>
</template>

<style lang="scss" scoped>
:deep(.n-form-item-label) {
  font-weight: bold;
}
</style>
